from django.http import JsonResponse
from meiduo_move_server.utils import request_utils
from meiduo_move_server.utils import img_utils
from meiduo_move_server.utils.mysql_utils import MySQLUtils
from meiduo_move_server import project_constants as p_const
from meiduo_move_server.utils import data_type_change_utils
from user.utils import jwt_utils


def addOrderInfo(req):
    """
    向数据库中添加订单信息
    """
    body = request_utils.getPostDataToDict(req.body)
    orderInfoArr = body.get('orderInfoArr')
    for orderInfo in orderInfoArr:
        cartInfoId = orderInfo.get('cartInfoId')
        orderStatus = orderInfo.get('orderStatus')
        goodsNumber = orderInfo.get('goodsNumber')
        selectParam = orderInfo.get('selectParam')
        payMoney = orderInfo.get('payMoney')
        token = orderInfo.get('token')
        userId = jwt_utils.get_payload(token).get('userId')
        goodsId = orderInfo.get('goodsId')
        userReceiveAddressId = orderInfo.get('userReceiveAddressId')
        sql = """
        CALL p_insert_order_info(%s, %s, %s, %s, %s, %s, %s, %s)
        """
        row_count = MySQLUtils.update(sql, (
        cartInfoId, orderStatus, goodsNumber, selectParam, payMoney, userId, goodsId, userReceiveAddressId))
        if row_count < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '订单信息提交失败'
            })
    # print(body)
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '订单信息提交成功'
    })


def payOrder(req):
    """
    支付订单
    """
    body = request_utils.getPostDataToDict(req.body)
    # print(body)
    orderInfoArr = body.get('orderInfoArr')
    for orderInfo in orderInfoArr:
        # print(orderInfo)
        cartInfoId = orderInfo.get('cartInfoId')
        sql = """
        UPDATE order_info
        SET order_status = TRUE
        WHERE cart_info_id = %s;
        """
        row_count = MySQLUtils.update(sql, (cartInfoId,))
        # print(row_count)
        if row_count < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '支付失败'
            })
        goodsId = orderInfo.get('goodsId')
        goodsNumber = orderInfo.get('goodsNumber')
        sql = """
        UPDATE goods_info SET goods_sale_number = goods_sale_number + %s, goods_count = goods_count - %s WHERE id = %s;
        """
        row_count = MySQLUtils.update(sql, (goodsNumber, goodsNumber, goodsId))
        # print(row_count)
        if row_count < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '商品销售量更新失败'
            })
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '支付成功'
    })


def getOrderNumber(req):
    """
    获取用户待支付订单和待收货订单信息
    """
    body = request_utils.getPostDataToDict(req.body)
    token = body.get('token')
    userId = jwt_utils.get_payload(token).get('userId')
    # 获取待支付订单
    sql = """
    SELECT count(*) FROM order_info WHERE user_account_info_id = %s AND order_status = FALSE;
    """
    res_data = MySQLUtils.select(sql, (userId,))
    orderWaitPayCount = res_data.get('data')[0][0]
    # 获取待收货订单
    sql = """
    SELECT count(*) FROM order_info WHERE user_account_info_id = %s AND order_status = TRUE;
    """
    res_data = MySQLUtils.select(sql, (userId,))
    orderWaitReceiveCount = res_data.get('data')[0][0]
    # print(res_data)
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '获取待支付订单数和待收货订单数成功',
        'data': {
            'orderWaitPayCount': orderWaitPayCount,
            'orderWaitReceiveCount': orderWaitReceiveCount
        }
    })


def getOrderInfo(req):
    """
    获取全部订单信息
    """
    token = request_utils.getPostDataToDict(req.body).get('token')
    userId = jwt_utils.get_payload(token).get('userId')
    sql = """
    SELECT oi.id,                  # 订单编号
           oi.order_status,        # 订单状态
           gi.goods_name,          # 商品名
           gi.goods_price,         # 商品价格
           oi.goods_number,        # 购买的商品数量
           gi.goods_freight,       # 商品运费
           oi.select_param,        # 商品参数
           oi.pay_money,           # 支付金额
           oi.receive_name,        #收货人姓名
           oi.receive_telephone,   # 电话号码
           oi.create_time,         # 订单创建时间
           oi.pay_time,            #  订单支付时间
           gi.id                   # 商品编号
    FROM order_info oi
             LEFT JOIN goods_info gi ON oi.goods_info_id = gi.id
             # LEFT JOIN user_receive_address_info urai ON oi.user_receive_address_id = urai.id
    WHERE oi.user_account_info_id = %s
    ORDER BY oi.id
            DESC;
    """
    res_data = MySQLUtils.select(sql, (userId,))
    if res_data.get('row_count') < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '暂无订单信息'
        })
    orderInfoArr = data_type_change_utils.tuple2dict(
        ['orderId', 'orderStatus', 'goodsName', 'goodsPrice', 'goodsNumber', 'goodsFreight', 'goodsParam', 'payMoney', 'receiveName',
         'receiveTelephone', 'orderCreateTime', 'orderPayTime', 'goodsId'],
        res_data.get('data')
    )
    for orderInfo in orderInfoArr:
        goodsId = orderInfo.get('goodsId')
        sql = """
        SELECT goods_picture_path
        FROM goods_picture_info
        WHERE goods_info_id = %s
        LIMIT 1;
        """
        res_data = MySQLUtils.select(sql, (goodsId,))
        orderInfo['goodsPicturePath'] = res_data.get('data')[0][0]
    # print(orderInfoArr)
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '获取订单信息成功',
        'data': orderInfoArr
    })


def deleteOrderById(req):
    """
    通过id删除订单
    """
    orderId = req.GET.get('orderId')
    sql = """
    DELETE FROM order_info WHERE id = %s;
    """
    row_count = MySQLUtils.update(sql, (orderId,))
    if row_count < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '订单删除失败'
        })
    # print(orderId)
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '订单删除成功'
    })


def payOrderById(req):
    """
    通过订单编号修改订单为已支付
    """
    orderId = req.GET.get('orderId')
    sql = """
        UPDATE order_info SET order_status = TRUE, pay_time = NOW() WHERE id = %s;
        """
    row_count = MySQLUtils.update(sql, (orderId,))
    if row_count < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '订单支付失败'
        })
    goodsId = req.GET.get('goodsId')
    goodsNumber = req.GET.get('goodsNumber')
    sql = """
            UPDATE goods_info SET goods_sale_number = goods_sale_number + %s, goods_count = goods_count - %s WHERE id = %s;
            """
    row_count = MySQLUtils.update(sql, (goodsNumber, goodsNumber, goodsId))
    # print(row_count)
    if row_count < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '商品销售量更新失败'
        })
    # print(orderId)
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '订单支付成功'
    })